<template>
 <Transition :name="transition" @enter="updateHeight" @after-leave="destroyComponent">
  <div
    class="dh-message"
    :class="{
      [`dh-message--${type}`]: type,
      'is-close': isClose,
    }"
    role="alert"
    v-show="isShow"
    ref="messageRef"
    :style="cssStyle"
    @mouseenter="clearTimer"
    @mouseleave="isShowMessage"
  >
    <div class="dh-message__content">
  
      <slot>
        <Icon :icon="icon" v-if="icon" class="dh-message__icon"></Icon>
        <RenderVnode :v-node="message" v-if="message"></RenderVnode>
      </slot>
    </div>
    <div class="dh-message__close" v-if="isClose">
      <Icon @click.stop="isShow = false" icon="xmark"></Icon>
    </div>
  </div>
 </Transition>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed , nextTick } from "vue";
//引入封装好的render组件
import RenderVnode from "../conmon/RenderFun";
//引入icon组件
import Icon from "../Icon/Icon.vue";
//引入方法
import { messageLast, getOffset } from "./methods";
//引入数据类型
import type { MessageProps } from "./type";
//引入辅助方法
import useEventLinsner from '@/hooks/useEventLinsner'
//接收数据
const props = withDefaults(defineProps<MessageProps>(), {
  type: "info",
  message: "这是一条消息提示",
  duration: 3000,
  isClose: false,
  offset: 20,
  transition: "fade-up",
});
//控制message组件的显示与隐藏
let isShow = ref(false);
//message组件实例
let messageRef = ref<HTMLDivElement>();
//基础高度，默认为0
let baseHeight = ref(0);
//上一个message底部距离顶部的距离
let offset = computed(() => getOffset(props.id!));

//使用的top高度
let topOffset = computed(() => {
  return offset.value + props.offset;
});
//下一个offset的值
let bottomOffset = computed(() => {
  return baseHeight.value + topOffset.value;
});
let cssStyle = computed(() => {
  return {
    top: topOffset.value + "px",
    zIndex:props.zIndex
  };
});

let timer:any
//控制message组件的显示与隐藏
const isShowMessage = () => {
  //如果props的duration为0，则一直显示message组件
  if (props.duration === 0) return;
  // console.log(111);
  
  timer = setTimeout(() => {
    isShow.value = false;
    //控制message组件的显示与隐藏
  }, props.duration);
 
  
};
const clearTimer = ()=>{
  // console.log(timer);
  // console.log(timer);
  clearTimeout(timer) 
}
//挂载时控制组件显示
onMounted( async () => {
  isShow.value = true;
  //调用控制message组件的显示与隐藏的函数
  isShowMessage();

});
function keydown(e: Event) {
  const event = e as KeyboardEvent;
  if(event.code === 'Escape') {
    isShow.value = false;
  }
}
useEventLinsner(document,'keydown',keydown)
function destroyComponent() {
    //调用props的onClose函数，卸载组件
    props.Ondestroy!();
}
 function updateHeight() {

  baseHeight.value = messageRef.value!.getBoundingClientRect().height;
}
const closeMessage = () => {
  props.Ondestroy
}
defineExpose({
  bottomOffset,
  isShow,
  onDestory: closeMessage()
})
</script>

<style scoped>
</style>
